package com.typhoon.rpc.registry.zk;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.typhoon.rpc.registry.ServiceRegistry;
import com.typhoon.rpc.registry.constant.Constant;

public class ZkServiceRegistry implements ServiceRegistry {


    private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegistry.class);

    /**
     * zk客户端
     */
    private final ZkClient zkClient;

    public ZkServiceRegistry(String zkAddress) {
        // 创建 ZooKeeper 客户端
        zkClient = new ZkClient(zkAddress, Constant.ZK_SESSION_TIMEOUT, Constant.ZK_CONNECTION_TIMEOUT);
        LOGGER.debug("connect zookeeper");
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        // 创建 registry 节点（持久）
        String registryPath = Constant.ZK_REGISTRY_PATH;
        if (!zkClient.exists(registryPath)) {//如果不存在根节点,创建持久根节点
            zkClient.createPersistent(registryPath);
            LOGGER.debug("create registry node: {}", registryPath);
        }
        // 创建 service 节点（持久）
        String servicePath = registryPath + "/" + serviceName;//服务节点=根节点/服务名称
        if (!zkClient.exists(servicePath)) {//如果服务节点不存在或者第一次注册,创建持久服务节点
            zkClient.createPersistent(servicePath);
            LOGGER.debug("create service node: {}", servicePath);
        }
        // 创建 address 节点（临时）
        String addressPath = servicePath + "/address-";//每一次有服务注册,创建临时节点
        //TODO 是否存在同一个服务实例重复注册
        String addressNode = zkClient.createEphemeralSequential(addressPath, serviceAddress);
        LOGGER.debug("create address node: {}", addressNode);
    }

}
